import streamlit as st
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from datetime import datetime
from io import BytesIO

class VerificationView:
    """数据核验视图类"""
    
    def __init__(self):
        self.page_size = 20
        self._init_session_state()
    
    def _init_session_state(self):
        """初始化session state"""
        defaults = {
            'verification_data': None,
            'verification_annotations': {},
            'temp_annotations': {},
            'verification_results': None,
            'verification_file_uploaded': False,
            'selected_row_index': None,
            'current_page': 0,
            'error_type_options': [
                "数据缺失", "格式错误", "数值异常", "逻辑错误", 
                "重复数据", "不一致", "超出范围", "其他"
            ],
            'ai_fields': []
        }
        
        for key, default_value in defaults.items():
            if key not in st.session_state:
                st.session_state[key] = default_value
    
    def _init_temp_annotations(self):
        """初始化临时标注存储"""
        if 'temp_annotations' not in st.session_state:
            st.session_state.temp_annotations = {}
    
    def render(self):
        """渲染数据核验页面"""
        st.markdown("<h1 class='main-header'>数据核验</h1>", unsafe_allow_html=True)
        
        # 文件上传区域
        self._render_file_upload()
        
        # 如果文件已上传，显示核验界面
        if st.session_state.verification_file_uploaded and st.session_state.verification_data is not None:
            self._render_verification_interface()
    
    def _render_file_upload(self):
        """渲染文件上传区域"""
        st.subheader("📁 上传核验文件")
        
        uploaded_file = st.file_uploader(
            "选择Excel文件（格式需与target文件一致）",
            type=['xlsx', 'xls'],
            help="上传的文件将与当前处理的target.xlsx文件隔离，防止数据污染"
        )
        
        if uploaded_file is not None:
            try:
                # 读取上传的Excel文件
                df = pd.read_excel(uploaded_file, header=1)
                st.session_state.verification_data = df
                st.session_state.verification_file_uploaded = True
                
                st.success(f"✅ 文件上传成功！共 {len(df)} 行数据")
                
            except Exception as e:
                st.error(f"❌ 文件读取失败：{str(e)}")
                return
    
    def _render_verification_interface(self):
        """渲染核验界面"""
        df = st.session_state.verification_data
        
        st.markdown("---")
        st.subheader("📝 数据核验与标注")
        
        # 检查是否有数据
        if len(df) == 0:
            st.warning("⚠️ 暂无数据需要核验")
            return
        
        # 核验进度
        total_cells = len(df) * len(df.columns)
        annotated_cells = len(st.session_state.verification_annotations)
        
        col1, col2 = st.columns(2)
        with col1:
            st.metric("总数据行", len(df))
        with col2:
            st.metric("已标注错误", annotated_cells)
        
        # 数据表格展示与标注
        st.subheader("📋 数据表格（选择行后在下方选择具体字段进行标注）")
        
        # 分页显示
        rows_per_page = 20
        total_pages = (len(df) - 1) // rows_per_page + 1
        
        page = st.selectbox("选择页面", range(1, total_pages + 1), format_func=lambda x: f"第 {x} 页")
        start_idx = (page - 1) * rows_per_page
        end_idx = min(start_idx + rows_per_page, len(df))
        
        page_df = df.iloc[start_idx:end_idx].copy()
        
        # 为已标注的单元格创建样式化显示
        styled_df = self._create_styled_dataframe(page_df, start_idx)
        
        st.write(f"显示第 {start_idx + 1} - {end_idx} 行数据")
        st.write("💡 提示：已标注错误的单元格前会显示 ❌ 标记")
        
        # 使用可选择行的数据表格
        selection = st.dataframe(
            styled_df,
            use_container_width=True,
            on_select="rerun",
            selection_mode="single-row",
            key=f"verification_table_page_{page}"
        )
        
        # 导出功能
        self._render_export_section(df)
        
        # 处理行选择
        if selection and 'selection' in selection and selection['selection']['rows']:
            selected_rows = selection['selection']['rows']
            if selected_rows:
                selected_row_in_page = selected_rows[0]
                selected_row_idx = start_idx + selected_row_in_page
                
                st.success(f"✅ 已选中第 {selected_row_idx + 1} 行")
                
                # 显示选中行的详细信息和字段选择
                self._render_row_annotation_panel(selected_row_idx)
        
        # 显示已标注错误的汇总
        self._render_annotation_summary()
    
    def _create_styled_dataframe(self, df_input, start_row_idx=None):
        """创建带样式的DataFrame用于显示"""
        styled_data = df_input.copy()
        
        # 为每个已标注的单元格添加标记
        for (row_idx, col_name), annotation in st.session_state.verification_annotations.items():
            # 如果是分页数据，需要调整行索引
            if start_row_idx is not None:
                if start_row_idx <= row_idx < start_row_idx + len(df_input):
                    page_row_idx = row_idx - start_row_idx
                    if col_name in styled_data.columns:
                        original_value = styled_data.iloc[page_row_idx][col_name]
                        # 确保列为 object 类型以避免 dtype 不兼容警告
                        if styled_data[col_name].dtype != 'object':
                            styled_data[col_name] = styled_data[col_name].astype('object')
                        styled_data.iloc[page_row_idx, styled_data.columns.get_loc(col_name)] = f"❌ {original_value}"
            else:
                # 完整数据的情况
                if row_idx < len(df_input) and col_name in styled_data.columns:
                    original_value = styled_data.iloc[row_idx][col_name]
                    # 确保列为 object 类型以避免 dtype 不兼容警告
                    if styled_data[col_name].dtype != 'object':
                        styled_data[col_name] = styled_data[col_name].astype('object')
                    styled_data.iloc[row_idx, styled_data.columns.get_loc(col_name)] = f"❌ {original_value}"
        
        return styled_data
    
    def _create_complete_styled_dataframe(self):
        """创建完整的带样式数据"""
        df = st.session_state.verification_data
        return self._create_styled_dataframe(df, start_row_idx=None)
    
    def _create_annotated_dataframe(self, df):
        """创建带有标注信息的DataFrame"""
        annotated_df = df.copy()
        
        # 添加错误标注列
        annotated_df['错误标注'] = ''
        
        for (row_idx, col_name), annotation in st.session_state.verification_annotations.items():
            if row_idx < len(annotated_df):
                current_annotation = annotated_df.iloc[row_idx]['错误标注']
                new_annotation = f"{col_name}: {annotation['error_type']} - {annotation['note']}"
                
                if current_annotation:
                    annotated_df.iloc[row_idx, annotated_df.columns.get_loc('错误标注')] = f"{current_annotation}; {new_annotation}"
                else:
                    annotated_df.iloc[row_idx, annotated_df.columns.get_loc('错误标注')] = new_annotation
        
        return annotated_df
    
    def _create_error_summary(self):
        """创建错误汇总报告"""
        df = st.session_state.verification_data
        error_data = []
        
        for (row_idx, col_name), annotation in st.session_state.verification_annotations.items():
            # 获取委托单号（假设在第1列，索引为0）
            try:
                # 确保行索引在有效范围内
                if row_idx < len(df):
                    # 获取第1列的值作为委托单号
                    wt = df.iloc[row_idx, df.columns.get_loc('委托单号')] if '委托单号' in df.columns else "未知"
                else:
                    wt = "未知"
            except:
                wt = "未知"
            error_data.append({
                '行号': row_idx + 1,
                '委托单号': wt,
                '字段名': col_name,
                '错误类型': annotation['error_type'],
                '错误描述': annotation['note'],
                '标注时间': annotation.get('timestamp', ''),
                '原始值': annotation.get('cell_value', '')
            })
        
        return pd.DataFrame(error_data)
    
    def _render_export_section(self, df):
        """渲染导出功能区域"""
        
        # 导出类型选择
        export_type = st.selectbox(
            "选择导出内容",
            ["完整展示数据", "仅带标注数据", "错误汇总报告"],
            help="选择要导出的数据类型"
        )
        
        # 导出格式选择
        export_format = st.selectbox(
            "选择导出格式",
            ["CSV", "Excel"],
            help="选择导出文件格式"
        )
        
        # 导出按钮
        if st.button("导出数据", type="primary", use_container_width=True):
            self._export_data(export_type, export_format, df)
    
    def _export_data(self, export_type, export_format, df):
        """执行数据导出"""
        try:
            # 根据选择的类型准备数据
            if export_type == "完整展示数据":
                export_df = self._create_complete_styled_dataframe()
                filename_prefix = "complete_data"
                
            elif export_type == "仅带标注数据":
                export_df = self._create_annotated_dataframe(df)
                filename_prefix = "annotated_data"
                
            elif export_type == "错误汇总报告":
                export_df = self._create_error_summary()
                filename_prefix = "error_summary"
            
            # 检查数据是否为空
            if len(export_df) == 0:
                st.warning(f"⚠️ {export_type}为空，无法导出")
                return
            
            # 根据格式生成文件
            timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
            
            if export_format == "CSV":
                file_data = export_df.to_csv(index=False, encoding='utf-8-sig')
                filename = f"{filename_prefix}_{timestamp}.csv"
                mime_type = "text/csv"
                
            elif export_format == "Excel":
                buffer = BytesIO()
                with pd.ExcelWriter(buffer, engine='openpyxl') as writer:
                    export_df.to_excel(writer, sheet_name='数据', index=False)
                file_data = buffer.getvalue()
                filename = f"{filename_prefix}_{timestamp}.xlsx"
                mime_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            
            # 显示下载按钮
            st.download_button(
                label=f"下载 {export_type} ({export_format})",
                data=file_data,
                file_name=filename,
                mime=mime_type,
                use_container_width=True
            )
            
            # 显示导出信息
            st.success(f"✅ 已准备 {export_type} 下载 ({len(export_df)} 行数据)")
            
        except Exception as e:
            st.error(f"❌ 导出失败: {str(e)}")
    
    def _render_row_annotation_panel(self, selected_row):
        """渲染行标注面板"""
        self._init_temp_annotations()
        
        st.markdown("---")
        st.subheader(f"🏷️ 选择要标注的字段")
        
        # 显示选中行的数据
        df = st.session_state.verification_data
        row_data = df.iloc[selected_row]
        
        st.write("**当前行数据：**")
        
        # 显示临时标注统计
        temp_count = len([k for k in st.session_state.temp_annotations.keys() if k[0] == selected_row])
        formal_count = len([k for k in st.session_state.verification_annotations.keys() if k[0] == selected_row])
        
        if temp_count > 0:
            st.info(f"📝 当前有 {temp_count} 个临时标注待保存")
        
        # 创建自定义的字段展示
        for col_name in df.columns:
            cell_value = row_data[col_name]
            annotation = self._get_field_annotation(selected_row, col_name)
            
            # 使用expander来组织每个字段
            if annotation:
                if annotation['is_temp']:
                    # 临时标注显示
                    with st.expander(f"📝 {col_name}: {str(cell_value)[:50]}... ({annotation['error_type']}) [临时]", expanded=False):
                        st.write(f"**完整值**: {cell_value}")
                        st.write(f"**错误类型**: {annotation['error_type']}")
                        st.write(f"**备注**: {annotation.get('note', '无')}")
                        st.warning("⚠️ 这是临时标注，需要点击保存按钮才会正式保存")
                        
                        if st.button("🗑️ 移除临时标注", key=f"remove_temp_{selected_row}_{col_name}"):
                            del st.session_state.temp_annotations[(selected_row, col_name)]
                            st.success("✅ 已移除临时标注")
                            st.rerun()
                else:
                    # 正式标注显示
                    with st.expander(f"❌ {col_name}: {str(cell_value)[:50]}... ({annotation['error_type']}) [已保存]", expanded=False):
                        st.write(f"**完整值**: {cell_value}")
                        st.write(f"**错误类型**: {annotation['error_type']}")
                        st.write(f"**备注**: {annotation.get('note', '无')}")
                        
                        if st.button("🗑️ 移除标注", key=f"remove_{selected_row}_{col_name}"):
                            del st.session_state.verification_annotations[(selected_row, col_name)]
                            st.success("✅ 已移除标注")
                            st.rerun()
            else:
                with st.expander(f"{col_name}: {str(cell_value)[:50]}...", expanded=False):
                    st.write(f"**完整值**: {cell_value}")
                    
                    if st.button("🏷️ 标注错误", key=f"annotate_{selected_row}_{col_name}"):
                        st.session_state[f"show_annotation_form_{selected_row}_{col_name}"] = True
                        st.rerun()
        
        # 显示标注表单（如果有字段被选中）
        for col_name in df.columns:
            if st.session_state.get(f"show_annotation_form_{selected_row}_{col_name}", False):
                self._render_annotation_form(selected_row, col_name, row_data[col_name])
        
        # 临时标注管理按钮
        if temp_count > 0:
            st.markdown("---")
            st.markdown("### 📋 临时标注管理")
            
            col1, col2 = st.columns(2)
            
            with col1:
                if st.button("💾 保存所有临时标注", type="primary"):
                    self._save_all_temp_annotations()
                    st.rerun()
            
            with col2:
                if st.button("🗑️ 清空所有临时标注", type="secondary"):
                    self._clear_temp_annotations()
                    st.rerun()
    
    def _render_annotation_form(self, row_idx, col_name, cell_value):
        """渲染标注表单"""
        st.markdown(f"### 📝 标注字段：{col_name}")
        st.info(f"当前值：{cell_value}")
        
        with st.form(f"annotation_form_{row_idx}_{col_name}"):
            # 快速错误类型按钮
            st.write("**选择错误类型：**")
            
            col1, col2, col3, col4 = st.columns(4)
            
            error_type_selected = None
            
            with col1:
                if st.form_submit_button("🔤 格式不规范"):
                    error_type_selected = "格式不规范"
            
            with col2:
                if st.form_submit_button("❌ 信息缺失"):
                    error_type_selected = "信息缺失"
            
            with col3:
                if st.form_submit_button("🔀 识别错误"):
                    error_type_selected = "识别错误"
            
            with col4:
                if st.form_submit_button("📝 多义词"):
                    error_type_selected = "多义词"
            
            # 自定义错误类型
            st.write("**或选择/输入自定义错误类型：**")
            
            col1, col2 = st.columns(2)
            with col1:
                selected_error = st.selectbox(
                    "预设错误类型",
                    st.session_state.error_type_options,
                    key=f"select_error_{row_idx}_{col_name}"
                )
            
            with col2:
                custom_error = st.text_input(
                    "自定义错误类型",
                    key=f"custom_error_{row_idx}_{col_name}"
                )
            
            note = st.text_area(
                "备注说明",
                key=f"note_{row_idx}_{col_name}"
            )
            
            # 表单提交按钮
            col1, col2 = st.columns(2)
            
            with col1:
                if st.form_submit_button("✅ 确认标注", type="primary"):
                    final_error_type = custom_error if custom_error else (error_type_selected if error_type_selected else selected_error)
                    self._add_temp_annotation(row_idx, col_name, cell_value, final_error_type, note)
                    st.session_state[f"show_annotation_form_{row_idx}_{col_name}"] = False
                    st.rerun()
            
            with col2:
                if st.form_submit_button("❌ 取消"):
                    st.session_state[f"show_annotation_form_{row_idx}_{col_name}"] = False
                    st.rerun()
            
            # 处理快速按钮选择
            if error_type_selected:
                self._add_temp_annotation(row_idx, col_name, cell_value, error_type_selected, "快速标注")
                st.session_state[f"show_annotation_form_{row_idx}_{col_name}"] = False
                st.rerun()
    
    def _add_temp_annotation(self, row_idx, col_name, cell_value, error_type, note):
        """添加临时标注"""
        if 'temp_annotations' not in st.session_state:
            st.session_state.temp_annotations = {}
        
        st.session_state.temp_annotations[(row_idx, col_name)] = {
            'error_type': error_type,
            'note': note,
            'cell_value': str(cell_value),
            'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        }
        st.success(f"✅ 已暂存标注 '{col_name}' 字段为：{error_type}")
    
    def _save_all_temp_annotations(self):
        """保存所有临时标注到正式标注区域"""
        if 'temp_annotations' not in st.session_state:
            return
        
        # 将临时标注合并到正式标注
        for key, value in st.session_state.temp_annotations.items():
            st.session_state.verification_annotations[key] = value
        
        # 清空临时标注
        saved_count = len(st.session_state.temp_annotations)
        st.session_state.temp_annotations = {}
        
        st.success(f"✅ 已保存 {saved_count} 个标注到正式区域")
    
    def _clear_temp_annotations(self):
        """清空所有临时标注"""
        if 'temp_annotations' in st.session_state:
            cleared_count = len(st.session_state.temp_annotations)
            st.session_state.temp_annotations = {}
            st.success(f"✅ 已清空 {cleared_count} 个临时标注")
    
    def _get_field_annotation(self, row_idx, col_name):
        """获取字段标注（优先返回临时标注）"""
        if (row_idx, col_name) in st.session_state.get('temp_annotations', {}):
            annotation = st.session_state.temp_annotations[(row_idx, col_name)].copy()
            annotation['is_temp'] = True
            return annotation
        elif (row_idx, col_name) in st.session_state.verification_annotations:
            annotation = st.session_state.verification_annotations[(row_idx, col_name)].copy()
            annotation['is_temp'] = False
            return annotation
        return None
    
    def _render_annotation_summary(self):
        """渲染标注汇总"""
        if not st.session_state.verification_annotations:
            return
        
        st.markdown("---")
        st.subheader("📋 标注汇总")
        
        # 统计信息
        error_types = {}
        field_errors = {}
        
        for (row_idx, col_name), annotation in st.session_state.verification_annotations.items():
            error_type = annotation['error_type']
            error_types[error_type] = error_types.get(error_type, 0) + 1
            field_errors[col_name] = field_errors.get(col_name, 0) + 1
        
        col1, col2, col3 = st.columns(3)
        with col1:
            st.metric("总标注数", len(st.session_state.verification_annotations))
        with col2:
            st.metric("错误类型数", len(error_types))
        with col3:
            st.metric("涉及字段数", len(field_errors))
        
        # 错误类型和字段分布
        if len(error_types) > 1:
            col1, col2 = st.columns(2)
            
            with col1:
                error_df = pd.DataFrame(list(error_types.items()), columns=['错误类型', '数量'])
                fig = px.bar(error_df, x='错误类型', y='数量', title="错误类型分布")
                fig.update_xaxes(tickangle=45)
                st.plotly_chart(fig, use_container_width=True)
            
            with col2:
                field_df = pd.DataFrame(list(field_errors.items()), columns=['字段名', '错误数量'])
                fig_field = px.bar(field_df, x='字段名', y='错误数量', title="字段错误分布")
                fig_field.update_xaxes(tickangle=45)
                st.plotly_chart(fig_field, use_container_width=True)
        
        # 详细标注列表（可折叠）
        with st.expander("📝 查看详细标注列表", expanded=False):
            annotations_data = []
            for (row, col), annotation in st.session_state.verification_annotations.items():
                annotations_data.append({
                    '行号': row + 1,
                    '列名': col,
                    '单元格值': annotation['cell_value'],
                    '错误类型': annotation['error_type'],
                    '备注': annotation['note'],
                    '标注时间': annotation.get('timestamp', '')
                })
            
            annotations_df = pd.DataFrame(annotations_data)
            st.dataframe(annotations_df, use_container_width=True)
        
        # 批量操作
        st.markdown("**批量操作：**")
        col1, col2 = st.columns(2)
        
        with col1:
            if st.button("🗑️ 清空所有标注", type="secondary"):
                if st.session_state.verification_annotations:
                    st.session_state.verification_annotations = {}
                    st.success("✅ 已清空所有标注")
                    st.rerun()
        
        with col2:
            if st.button("📊 生成核验结果", type="primary"):
                if st.session_state.verification_annotations:
                    self._generate_verification_results()
                    st.success("✅ 核验结果已生成！")
                    st.rerun()
                else:
                    st.warning("⚠️ 请先标注一些错误数据")
    
    def _generate_verification_results(self):
        """生成核验结果分析,总单元格数、字段错误数、字段准确率、委托单号错误数，排除错误数据"""
        df = st.session_state.verification_data
        annotations = st.session_state.verification_annotations
        
        # 计算基础统计
        total_records = len(df)
        total_fields = len(df.columns)
        # 计算总的非空单元格数
        total_cells = 0
        for col in df.columns:
            if col not in st.session_state['ai_fields'] or col in st.session_state['skipped_fields']:
                continue
            # 计算该列中非空且不为NaN的单元格数量
            non_empty_count = df[col].apply(lambda x: pd.notna(x) and str(x).strip() != '').sum()
            total_cells += non_empty_count
        
        # 按字段统计错误
        field_errors = {}
        error_types_count = {}
        
        for (row, col), annotation in annotations.items():
            # 字段错误统计
            if col not in st.session_state['ai_fields'] or col in st.session_state['skipped_fields']:
                continue
            if col not in field_errors:
                field_errors[col] = 0
            field_errors[col] += 1
            
            # 错误类型统计
            error_type = annotation['error_type']
            if error_type not in error_types_count:
                error_types_count[error_type] = 0
            error_types_count[error_type] += 1

        error_cells = sum(field_errors.values())
        accuracy_rate = (total_cells - error_cells) / total_cells * 100 if total_cells > 0 else 0
        
        # 计算所需字段的准确率
        field_accuracy = {}
        for col in df.columns:
            if col not in st.session_state['ai_fields'] or col in st.session_state['skipped_fields']:
                continue
            # 该字段的非空单元格数量
            field_total = df[col].apply(lambda x: pd.notna(x) and str(x).strip() != '').sum()
            field_error = field_errors.get(col, 0)
            accuracy = ((field_total - field_error) / field_total * 100 )if field_total > 0 else 100
            field_accuracy[col] = (accuracy, field_total)
        
        # 委托单错误统计（假设有委托单号列）
        delegation_errors = {}
        if '委托单号' in df.columns:
            for (row, col), annotation in annotations.items():
                if col not in st.session_state['ai_fields'] or col in st.session_state['skipped_fields']:
                    continue
                delegation_no = df.iloc[row]['委托单号']
                if delegation_no not in delegation_errors:
                    delegation_errors[delegation_no] = 0
                delegation_errors[delegation_no] += 1
        
        # 保存结果到session state
        st.session_state.verification_results = {
            'total_records': total_records,
            'total_fields': total_fields,
            'total_cells': total_cells,
            'error_cells': error_cells,
            'accuracy_rate': accuracy_rate,
            'field_errors': field_errors,
            'field_accuracy': field_accuracy,
            'error_types_count': error_types_count,
            'delegation_errors': delegation_errors
        }
    
    def render_verification_results(self):
        """渲染核验结果页面"""
        if st.session_state.verification_results is None:
            st.warning("⚠️ 请先生成核验结果")
            return
        
        results = st.session_state.verification_results
        st.subheader("核验结果分析")
        
        # 基础指标
        col1, col2, col3, col4 = st.columns(4)
        with col1:
            st.metric("总记录数", results['total_records'])
        with col2:
            st.metric("错误单元格", results['error_cells'])
        with col3:
            st.metric("有效单元格数", f"{results['total_cells']}")
        with col4:
            st.metric("整体准确率", f"{results['accuracy_rate']:.2f}%")
        
        # AI识别字段覆盖率分析
        st.subheader("AI识别字段准确率分析")
        
        field_accuracy_data = []
        for field, accuracy_tuple in results['field_accuracy'].items():
            if isinstance(accuracy_tuple, tuple):
                accuracy, total = accuracy_tuple

            error_count = results['field_errors'].get(field, 0)
            field_accuracy_data.append({
                '字段名称': field,
                '准确率': f"{accuracy:.2f}%",
                '错误数量': error_count,
                '出现次数': total
            })
        
        field_df = pd.DataFrame(field_accuracy_data)
        st.dataframe(field_df, use_container_width=True)
        
        # 字段准确率柱状图
        col1, col2 = st.columns(2)
        
        with col1:
            st.subheader("字段准确率柱状图")
            fig_bar = px.bar(
                field_df,
                x='字段名称',
                y='准确率',
                title="各字段识别准确率",
                color='准确率',
                color_continuous_scale='RdYlGn'
            )
            fig_bar.update_xaxes(tickangle=45)
            fig_bar.update_layout(height=400)
            st.plotly_chart(fig_bar, use_container_width=True)
        
        with col2:
            st.subheader("整体准确率分布")
            fig_pie = go.Figure(data=[go.Pie(
                labels=['正确', '错误'],
                values=[results['total_cells'] - results['error_cells'], results['error_cells']],
                hole=.4,
                marker_colors=['#2ecc71', '#e74c3c']
            )])
            fig_pie.update_layout(
                title_text="整体数据准确率分布",
                annotations=[dict(text=f"准确率<br>{results['accuracy_rate']:.1f}%", 
                                x=0.5, y=0.5, font_size=15, showarrow=False)],
                height=400
            )
            st.plotly_chart(fig_pie, use_container_width=True)
        
        # 错误类型分析
        if results['error_types_count']:
            st.subheader("错误类型分析")
            
            col1, col2 = st.columns(2)
            
            with col1:
                error_types_df = pd.DataFrame(
                    list(results['error_types_count'].items()),
                    columns=['错误类型', '出现次数']
                )
                
                fig_error_bar = px.bar(
                    error_types_df,
                    x='错误类型',
                    y='出现次数',
                    title="各类错误出现次数",
                    color='出现次数',
                    color_continuous_scale='Reds'
                )
                fig_error_bar.update_xaxes(tickangle=45)
                st.plotly_chart(fig_error_bar, use_container_width=True)
            
            with col2:
                fig_error_pie = px.pie(
                    error_types_df,
                    values='出现次数',
                    names='错误类型',
                    title="错误类型分布占比"
                )
                st.plotly_chart(fig_error_pie, use_container_width=True)
        
        # 识别错误率最高的字段
        st.subheader("识别错误率最高的字段")
        
        field_error_rate = []
        for field, accuracy_tuple in results['field_accuracy'].items():
            if isinstance(accuracy_tuple, tuple):
                accuracy, total = accuracy_tuple     
            error_rate = 100 - accuracy
            error_count = results['field_errors'].get(field, 0)
            field_error_rate.append({
                '字段名称': field,
                '错误率': f"{error_rate:.2f}%",
                '错误数量': error_count,
                '出现次数': total
            })
        
        field_error_df = pd.DataFrame(field_error_rate)
        field_error_df = field_error_df.sort_values('错误率', ascending=False)
        
        st.dataframe(field_error_df.head(10), use_container_width=True)
        
        # 委托单号错误分析
        if results['delegation_errors']:
            st.subheader("委托单号错误分析 - Top 10")
            
            delegation_error_data = [
                {'委托单号': k, '错误字段数': v}
                for k, v in sorted(results['delegation_errors'].items(), key=lambda x: x[1], reverse=True)[:10]
            ]
            
            delegation_df = pd.DataFrame(delegation_error_data)
            
            fig_delegation = px.bar(
                delegation_df,
                x='委托单号',
                y='错误字段数',
                title="错误字段最多的委托单 Top 10",
                color='错误字段数',
                color_continuous_scale='Reds'
            )
            fig_delegation.update_xaxes(tickangle=45)
            st.plotly_chart(fig_delegation, use_container_width=True)
            
            st.dataframe(delegation_df, use_container_width=True)